﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using CefSharp;
using CefSharp.WinForms;
using Common.Model;
using Dapper.Contrib.Extensions;
using Newtonsoft.Json.Linq;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using pinduoduo.CefHandler;
using pinduoduo.Model;
using pinduoduo.Util;
using Sunny.UI;
using Tk.Soc.Share.Common.Helpers;

namespace pinduoduo
{
    public partial class BrowserFrom : UIForm
    {

        private ChromiumWebBrowser AccountChromeBrowser;

        private RequestContext AccountContext;

        public MyRequestHandler myRequestHandler;
        public Action action;
        public Action<string> SetGoodIdAction;
        private int timeout = 5000;
        private UInt64 queryGoodsDetailIdentifier = 0;
        private UInt64 queryGoodsShareInfoIdentifier = 0;

        public string ZhiFuPassword { get; set; }

        private int type;

        private bool isAutoPay = false;



        public BrowserFrom(bool isAutoPay = false)
        {
            this.isAutoPay = isAutoPay;
            InitializeComponent();
            InitializeAccountChromium();
        }

        public async void AutoPay(string url, string password, bool isClose = false, int timeout = 5000)
        {
            this.panel1.Width = 460;
            this.panel1.Height = 658;
            this.Text = "支付";
            AccountChromeBrowser.Load(url);
            this.Width = 466;
            this.Height = 698;
            ChromeDriverService service = ChromeDriverService.CreateDefaultService();
            service.LogPath = AppDomain.CurrentDomain.BaseDirectory + "drive";
            IWebDriver driver = await GetDriver(service);

            if (driver == null)
            {
                ShowErrorNotifier("自动支付驱动异常，请重试或重启软件!");
                return;
            }
            try
            {
                //driver.Navigate().GoToUrl(url);
                var zhifuButton = By.XPath("//*[@id=\"cashierPreConfirm\"]/div[2]/button");
                driver.FindElement(zhifuButton).Click();
                var payInput = By.XPath("//*[@id=\"pwd_unencrypt\"]");
                driver.SwitchTo().DefaultContent();
                driver.FindElement(payInput).SendKeys(password);
                Thread.Sleep(2000);

                string nextUrl = driver.Url;
                if (nextUrl.Contains("https://mclient.alipay.com/h5/cashierPay.htm?awid="))
                {
                    int delay = 0;
                    while (true)
                    {
                        if (driver.PageSource.Contains("短信校验码") && driver.PageSource.Contains("收到的短信校验码"))
                        {
                            ShowErrorNotifier("任务失败");
                            break;
                        }
                        var successEl = driver.FindElement(By.ClassName("J-success"));

                        if (successEl != null && successEl.Displayed)
                        {
                            ShowSuccessNotifier("任务成功");

                            if (isClose)
                            {
                                this.DialogResult = DialogResult.OK;
                                this.Close();
                            }

                            return;
                        }
                        await Task.Delay(500);
                        delay += 500;
                        if (delay > timeout * 1000)
                        {
                            break;
                        }
                    }

                    ShowErrorNotifier("任务失败");
                }
                else
                {
                    ShowErrorNotifier("任务失败");
                }
            }
            catch (Exception e)
            {
                LogHelper.Logger.Error("自动支付异常：", e);
                ShowErrorNotifier("任务失败");
            }
            finally
            {
                await Task.Run(() =>
                {
                    driver?.Close();
                    driver?.Quit();
                    driver?.Dispose();
                });

            }
        }

        public static async Task<IWebDriver> GetDriver(ChromeDriverService chromeDriverService)
        {
            IWebDriver driver = null;
            await Task.Run(() =>
            {
                try
                {
                    ChromeOptions options = new ChromeOptions();
                    options.DebuggerAddress = "127.0.0.1:22222";
                    options.AddArgument("no-sandbox");
                    chromeDriverService.HideCommandPromptWindow = true;
                    driver = new ChromeDriver(chromeDriverService, options, TimeSpan.FromSeconds(10));
                }
                catch (Exception e)
                {
                    if (driver != null)
                    {
                        driver?.Close();
                        driver?.Quit();
                        driver?.Dispose();
                    }
                    driver = null;
                }
            });
            return driver;
        }

        public void LoadUrl(string url, int timeout, int type = (int)PddGoodSource.Pifa)
        {
            this.timeout = timeout;
            this.type = type;

            AccountChromeBrowser.Load(url);

            if (type == (int)PddGoodSource.DuoDuo)
            {
                this.Text = "多多商品获取";
                this.panel1.Width = 460;
                this.panel1.Height = 658;

                this.Width = 466;
                this.Height = 698;

            }
            else if (type == (int)PddGoodSource.ZhiBo)
            {
                this.Text = "直播商品获取";
                this.panel1.Width = 460;
                this.panel1.Height = 658;

                this.Width = 466;
                this.Height = 698;
            }
            else if (type == 9)
            {
                this.panel1.Width = 460;
                this.panel1.Height = 658;
                this.Text = "支付";

                this.Width = 466;
                this.Height = 698;
            }
            else
            {
                this.Text = "批发商品获取";
                this.panel1.Width = 1125;
                this.panel1.Height = 603;

                this.Width = 1131;
                this.Height = 644;
            }
        }

        public static string PaserQueryGoodsShareInfo(string queryGoodsShareInfoData)
        {

            var jo = JObject.Parse(queryGoodsShareInfoData);
            var success = jo["success"].ToString();
            if (success.ToLower() != "true")
            {
                return "";
            }
            var firstLadderStartValue = jo["result"]["firstLadderStartValue"].ToString();
            return firstLadderStartValue;
        }

        public async Task<bool> IsLoading(ChromiumWebBrowser chromiumWebBrowser, int timeout)
        {
            int delay = 0;
            while (true)
            {
                try
                {
                    var fd = myRequestHandler.Filters.FirstOrDefault(f => f.Name == "queryGoodsDetail");
                    //var queryGoodsShareInfoFd = myRequestHandler.Filters.FirstOrDefault(f => f.Name == "queryGoodsShareInfo");
                    var HasData = fd?.HasData;
                    //var queryGoodsShareInfoFdHasData = queryGoodsShareInfoFd?.HasData;

                    //if (HasData.GetValueOrDefault() && queryGoodsShareInfoFdHasData.GetValueOrDefault())
                    if (HasData.GetValueOrDefault())
                        {
                        //if (fd?.Identifier == queryGoodsDetailIdentifier || queryGoodsShareInfoFd.Identifier == queryGoodsShareInfoIdentifier)
                        if (fd?.Identifier == queryGoodsDetailIdentifier)
                        {
                        }
                        else
                        {
                            break;
                        }
                    }

                    await Task.Delay(100);
                    delay += 100;
                    if (delay > timeout * 1000)
                    {
                        return false;
                    }
                }
                catch
                {

                }


            }
            return true;
        }


        public async Task<bool> HtmlIsLoading(ChromiumWebBrowser chromiumWebBrowser, int timeout)
        {
            int delay = 0;
            while (true)
            {
                try
                {
                    if (chromiumWebBrowser.IsBrowserInitialized && chromiumWebBrowser.GetBrowser().IsLoading)
                    {
                        string html = await AccountChromeBrowser.GetSourceAsync();
                        if (html.Contains("支付宝付款") && html.Contains("确认付款"))
                        {
                            break;
                        }

                    }
                    await Task.Delay(100);
                    delay += 100;
                    if (delay > timeout * 1000)
                    {
                        return false;
                    }
                }
                catch (Exception e)
                {

                }


            }
            return true;
        }


        //初始化浏览器并启动
        public void InitializeAccountChromium()
        {

            AccountContext = new RequestContext(new RequestContextSettings()
            {
                CachePath = AppDomain.CurrentDomain.BaseDirectory + "caches\\global1\\",
                PersistSessionCookies = true,
                PersistUserPreferences = true
            });

            AccountChromeBrowser = new ChromiumWebBrowser("http://yangkeduo.com/", AccountContext);
            BrowserSettings browserSettings = new BrowserSettings();
            browserSettings.ApplicationCache = CefState.Enabled;

            AccountChromeBrowser.BrowserSettings = browserSettings;

            AccountChromeBrowser.KeyboardHandler = new CEFKeyBoardHander();

            if (!isAutoPay)
            {
                AccountChromeBrowser.FrameLoadEnd += AccountChromeBrowser_FrameLoadEnd;

                //要捕获的url， "mainPage"只是url的简称，不做计算用
                Dictionary<string, string> FilterUrls = new Dictionary<string, string>()
            {
                {"queryGoodsDetail","https://pifa.pinduoduo.com/pifa/goods/queryGoodsDetail" },
                {"queryGoodsShareInfo","https://pifa.pinduoduo.com/pifa/goods/queryGoodsShareInfo" },

            };

                #region  自定义捕获或过滤
                //new有很多重载方法，由于我这次用默认全是GET，所以没有定义请求类型
                myRequestHandler = new MyRequestHandler(FilterUrls, HttpMethod.POST);
                AccountChromeBrowser.RequestHandler = myRequestHandler;
                #endregion

            }


            this.panel1.Controls.Add(AccountChromeBrowser);


            AccountChromeBrowser.IsBrowserInitializedChanged += OnIsBrowserInitializedChanged;

            AccountChromeBrowser.Dock = DockStyle.Fill;
        }

        private void OnIsBrowserInitializedChanged(object sender, EventArgs args)
        {
            SetCookie(CefUtils.GetAccountContext());
        }

        private string pddurl = "http://yangkeduo.com/";

        public async void SetCookie(RequestContext AccountContext)
        {
            List<CefSharp.Cookie> cookies = await AccountContext.GetCookieManager(null).VisitUrlCookiesAsync(pddurl, true);

            foreach (var item in cookies)
            {
                await AccountChromeBrowser.GetCookieManager().SetCookieAsync(pddurl, item);
            }
        }

        //private PifaClientOrderCreate PaserOrderHtml(string html)
        //{
        //    Regex reg = new Regex("window.rawData= (?<key2>.*?)};");
        //    Match match = reg.Match(html);
        //    string tempStr = match.Groups["key2"].Value;
        //    if (string.IsNullOrWhiteSpace(tempStr))
        //    {
        //        MessageBox.Show("解析数据失败");
        //        return null;
        //    }
        //    PifaClientOrderCreate pifaClientOrderCreate = new PifaClientOrderCreate();
        //    pifaClientOrderCreate.sku_vos = new List<Sku_vosItem>();
        //    Sku_vosItem sku_VosItem = new Sku_vosItem();
        //    var jo = JObject.Parse(tempStr + " }");
        //    var goodsListStore = jo["store"]["goodsListStore"]["goodsList"].ToArray();
        //    var frontEnv = jo["store"]["envStore"]["frontEnv"].ToObject<int>();
        //    //var addressId = jo["store"]["addressInfoStore"]["addressId"].ToObject<double>();

        //    var goods = goodsListStore.FirstOrDefault();
        //    string goods_id = goods["goodsId"].ToString();
        //    string group_id = goods["groupId"].ToString();
        //    string sku_id = goods["skuId"].ToString();
        //    string sku_number = goods["skuNumber"].ToString();

        //    sku_VosItem.goods_id = double.Parse(goods_id);
        //    sku_VosItem.group_id = double.Parse(group_id);
        //    sku_VosItem.sku_id = double.Parse(sku_id);
        //    sku_VosItem.sku_number = int.Parse(sku_number);
        //    pifaClientOrderCreate.front_env = frontEnv;
        //    pifaClientOrderCreate.sku_vos.Add(sku_VosItem);

        //    return pifaClientOrderCreate;
        //}

        private async void AccountChromeBrowser_FrameLoadEnd(object sender, FrameLoadEndEventArgs e)
        {
            try
            {
                //支付界面
                if (type == 9)
                {
                    //string html= await AccountChromeBrowser.GetSourceAsync();
                    //if (html.Contains("支付宝付款") && html.Contains("确认付款"))
                    //{
                    //    Browser.Delay(300);
                    //    Browser.MouseLeftByHtmlElement("getElementsByText('确认付款','button')", AccountChromeBrowser, true);
                    //    bool res = Browser.MouseLeftByHtmlElement("document.getElementById('pwd_unencrypt')", AccountChromeBrowser, true);
                    //    if (res)
                    //    {
                    //        Browser.Delay(300);
                    //        SendKeys.SendWait(ZhiFuPassword);
                    //    }
                    //}

                    //Browser.Delay(300);
                    //SendKeys.SendWait(ZhiFuPassword);
                }

                if (type == (int)PddGoodSource.DuoDuo)
                {
                    string url = "https://mobile.yangkeduo.com/duo_coupon_landing.html?goods_id=234288048615&pid=21076657_209268512&goods_sign=Y9j2lObpF3NTlcXxwuvZGwHcytoZs5sB_JQQCQDLb1i&cpsSign=CC_210525_21076657_209268512_b8e4518463245662988032bbc29c611b&duoduo_type=2";
                    if (!e.Url.Contains("https://mobile.yangkeduo.com/duo_coupon_landing.html?goods_id="))
                    {
                        return;
                    }
                    string script = @"(function() { return  window.rawData.store;})()";

                    await AccountChromeBrowser.EvaluateScriptAsync(script).ContinueWith(x =>
                    {
                        var response = x.Result;

                        if (response.Success && response.Result != null)
                        {
                            var jo = JObject.FromObject(response.Result);
                            string mallId = jo["couponData"]["mallId"].ToString();
                            string mktToken = jo["couponData"]["goodsVo"]["mktToken"].ToString();
                            string mktTrSc = jo["couponData"]["goodsVo"]["mktTrSc"].ToString();
                            string mktDomain = jo["couponData"]["goodsVo"]["mktDomain"].ToString();
                            var goods_id = jo["query"]["goods_id"].ToString();
                            var pid = jo["query"]["pid"].ToString();
                            var cpsSign = jo["query"]["cpsSign"].ToString();
                    

                            PddGood pddGood = new PddGood();
                            pddGood.good_id = goods_id;
                            pddGood.duo_duo_pid = pid;
                            pddGood.cps_sign = cpsSign;
                            pddGood.mall_id = mallId;
                            pddGood.mkt_domain = mktDomain;
                            pddGood.mkt_tr_sc = mktTrSc;
                            pddGood.mkt_tr_token = mktToken;
                            pddGood.type = (int)PddGoodSource.DuoDuo;
                            try
                            {
                                var groupTypes = jo["goods"]["groupTypes"];
                                if (groupTypes.Count() > 0)
                                {
                                    pddGood.gID2 = groupTypes[0]["groupID"].ToString();
                                }
                                if (groupTypes.Count() > 1)
                                {
                                    pddGood.gID1 = groupTypes[1]["groupID"].ToString();
                                }

                                var skus = jo["goods"]["skus"];
                                string skuJson = JsonHelper.SerializeObject(skus);
                                pddGood.sku = skuJson;
                            }
                            catch
                            {
                            }

                            PddGood pdd = DataBaseHelper.SqLiteDBCon.Get<PddGood>(goods_id);
                            if (pdd == null)
                            {
                                long reslut = DataBaseHelper.SqLiteDBCon.Insert(pddGood);
                            }
                            else
                            {
                                pddGood.SourceKeywords = pdd.SourceKeywords;

                                DataBaseHelper.SqLiteDBCon.Update<PddGood>(pddGood);
                            }
                            this.BeginInvoke(new Action(() =>
                            {
                                SetGoodIdAction?.Invoke(goods_id);
                                action?.Invoke();
                                MessageBox.Show("获取数据成功");
                            }));
                        }
                        return;
                    });
                }

                if (type == (int)PddGoodSource.ZhiBo)
                {
                    string url = "https://mobile.yangkeduo.com/duo_coupon_landing.html?goods_id=234288048615&pid=21076657_209268512&goods_sign=Y9j2lObpF3NTlcXxwuvZGwHcytoZs5sB_JQQCQDLb1i&cpsSign=CC_210525_21076657_209268512_b8e4518463245662988032bbc29c611b&duoduo_type=2";
                    if (!e.Url.Contains("https://mobile.yangkeduo.com/"))
                    {
                        return;
                    }
                    string script = @"(function() { return  window.rawData.store.initDataObj;})()";

                    await AccountChromeBrowser.EvaluateScriptAsync(script).ContinueWith(x =>
                    {
                        var response = x.Result;

                        if (response.Success && response.Result != null)
                        {
                            var jo = JObject.FromObject(response.Result);
                            try
                            {
                                var goods_id = jo["queries"]["goods_id"].ToString();


                                var _oc_n_mkt_tr_token = jo["queries"]["_oc_n_mkt_tr_token"].ToString();
                                var _oc_n_mkt_domain = jo["queries"]["_oc_n_mkt_domain"].ToString();
                                var _oc_n_mkt_tr_sc = jo["queries"]["_oc_n_mkt_tr_sc"].ToString();
                                var _oc_live_show_id = jo["queries"]["_oc_live_show_id"].ToString();
                                var refer_page_name = jo["queries"]["refer_page_name"]?.ToString();
                                var refer_page_id = jo["queries"]["refer_page_id"]?.ToString();
                                var refer_page_sn = jo["queries"]["refer_page_sn"]?.ToString();

                                PddGood pddGood = new PddGood();
                                pddGood.good_id = goods_id;
                                pddGood.type = (int)PddGoodSource.ZhiBo;
                                pddGood.live_show_id = _oc_live_show_id;
                                pddGood.mkt_domain = _oc_n_mkt_domain;
                                pddGood.mkt_tr_sc = _oc_n_mkt_tr_sc;
                                pddGood.mkt_tr_token = _oc_n_mkt_tr_token;

                                pddGood.refer_page_id = refer_page_id;
                                pddGood.refer_page_name = refer_page_name;
                                pddGood.refer_page_sn = refer_page_sn;

                                var groupTypes = jo["goods"]["groupTypes"];
                                if (groupTypes.Count() > 0)
                                {
                                    pddGood.gID2 = groupTypes[0]["groupID"].ToString();
                                }
                                if (groupTypes.Count() > 1)
                                {
                                    pddGood.gID1 = groupTypes[1]["groupID"].ToString();
                                }

                                var skus = jo["goods"]["skus"];
                                string skuJson = JsonHelper.SerializeObject(skus);
                                pddGood.sku = skuJson;


                                PddGood pdd = DataBaseHelper.SqLiteDBCon.Get<PddGood>(goods_id);
                                if (pdd == null)
                                {
                                    long reslut = DataBaseHelper.SqLiteDBCon.Insert(pddGood);
                                }
                                else
                                {
                                    pddGood.SourceKeywords = pdd.SourceKeywords;

                                    DataBaseHelper.SqLiteDBCon.Update<PddGood>(pddGood);
                                }
                                this.BeginInvoke(new Action(() =>
                                {
                                    SetGoodIdAction?.Invoke(goods_id);
                                    action?.Invoke();
                                    MessageBox.Show("获取数据成功");
                                }));

                            }
                            catch
                            {
                            }
                        }
                        return;
                    });
                }


                if (type == (int)PddGoodSource.Pifa)
                {
                    https://mai.pinduoduo.com/mobile-wholesale/goods-detail.html?
                    if (!e.Url.Contains("https://pifa.pinduoduo.com/goods/detail/?gid=") && !e.Url.Contains("https://mai.pinduoduo.com/mobile-wholesale/goods-detail.html"))
                    {
                        return;
                    }
                    await Task.Run(async () =>
                    {
                        //await Task.Delay(timeout);
                        bool result = await IsLoading(AccountChromeBrowser, this.timeout);
                        if (!result)
                        {
                            MessageBox.Show("获取失败");
                            return;

                        }
                        var fd = myRequestHandler.Filters.FirstOrDefault(f => f.Name == "queryGoodsDetail");
                        //var queryGoodsShareInfoFd = myRequestHandler.Filters.FirstOrDefault(f => f.Name == "queryGoodsShareInfo");
                        var HasData = fd?.HasData;
                        //var queryGoodsShareInfoFdHasData = queryGoodsShareInfoFd?.HasData;

                        //if (HasData.GetValueOrDefault() && queryGoodsShareInfoFdHasData.GetValueOrDefault())
                        if (HasData.GetValueOrDefault())
                            {
                            var data = fd?.Filter?.DataStr;
                            //var queryGoodsShareInfoData = queryGoodsShareInfoFd?.Filter?.DataStr;
                            //string firstLadderStartValueStr = PaserQueryGoodsShareInfo(queryGoodsShareInfoData);
                            var jo = JObject.Parse(data);

                            var success = jo["success"].ToString();
                            if (success.ToLower() != "true")
                            {
                                MessageBox.Show("获取数据失败");
                                return;
                            }
                            //var success = jo["success"].ToString();
                            var goodsId = jo["result"]["goodsId"].ToString();
                            var goodsStageDiscounts = jo["result"]["goodsStageDiscounts"].ToArray();
                            var goodsStageDiscount =  goodsStageDiscounts.FirstOrDefault();
                            int firstLadderStartValue=2;
                            if (goodsStageDiscount != null) 
                            {
                              var stageStartValue =  goodsStageDiscount["stageStartValue"].ToString();

                                int.TryParse(stageStartValue, out firstLadderStartValue);
                            }
                            PddGood pddGood = new PddGood();
                            pddGood.good_id = goodsId;
                          
                       
                            pddGood.firstLadderStartValue = firstLadderStartValue;
                            var goodsSkuInfos = jo["result"]["goodsSkuInfos"];
                            string skuJson = JsonHelper.SerializeObject(goodsSkuInfos);

                            pddGood.sku = skuJson;
                            pddGood.type = (int)PddGoodSource.Pifa;

                            PddGood pdd = DataBaseHelper.SqLiteDBCon.Get<PddGood>(goodsId);
                            if (pdd == null)
                            {
                                long reslut = DataBaseHelper.SqLiteDBCon.Insert(pddGood);
                            }
                            else
                            {
                                pddGood.SourceKeywords = pdd.SourceKeywords;

                                DataBaseHelper.SqLiteDBCon.Update<PddGood>(pddGood);
                                //MessageBox.Show("获取数据成功");
                            }
                            queryGoodsDetailIdentifier = fd.Identifier;
                            //queryGoodsShareInfoIdentifier = queryGoodsShareInfoFd.Identifier;
                            this.BeginInvoke(new Action(() =>
                            {
                                action?.Invoke();
                                MessageBox.Show("获取数据成功");
                            }));

                        }

                    });
                }

            }
            catch (Exception ex)
            {
                LogHelper.Logger.Error("程序错误", ex);
            }

        }

        private void SKU_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (myRequestHandler != null)
            {
                myRequestHandler.Dispose();
            }
        }

    }
}
